#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <iostream>
#include <thread>
#include "global.h"
using namespace std;

class client
{
    private:
        int server_port;//服务器端口
        string server_ip;//服务器ip
        int sock;//与服务器建立连接的套接字描述符
    public:
        client(int port,string ip);
        ~client();
        void run();//启动客户端服务
        static void SendMsg(int conn);//发送线程
        static void RecvMsg(int conn);//接收线程
};

client::client(int port,string ip):server_port(port),server_ip(ip){}
client::~client(){
    close(sock);
}

void client::run(){

    // 1. 定义sockfd
    sock = socket(AF_INET,SOCK_STREAM, 0);

    // 定义sockaddr_in
    struct sockaddr_in servaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(server_port);  //服务器端口
    servaddr.sin_addr.s_addr = inet_addr(server_ip.c_str());  //服务器ip

    // 2. 连接服务器，成功返回0，错误返回-1
    if (connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        perror("connect");
        exit(1);
    }
    cout << "连接服务器成功\n";

    // 3. 创建发送线程和接收线程
    thread send_t(SendMsg,sock), recv_t(RecvMsg,sock);
    send_t.join();
    cout<<"发送线程已结束\n";
    recv_t.join();
    cout<<"接收线程已结束\n";
    return;
}

//注意，前面不用加static！
void client::SendMsg(int conn){
    while (1)
    {
        CommInfo cmd;
        memset(&cmd, 0, sizeof(cmd));
        cout << "0 注册，1登录：";
        int type;
        cin >> type;
        cmd.type = CmdType(type);
        cout << "用户名：";
        cin >> cmd.name;
        cout << "密码：";
        cin >> cmd.passwd;
        int ret = send(conn, &cmd, sizeof(cmd), 0); //发送
        //输入exit或者对端关闭时结束
        // if(strcmp(sendbuf,"exit")==0||ret<=0)
        //     break;
    }
}

//注意，前面不用加static！
void client::RecvMsg(int conn){
    //接收缓冲区
    char buffer[1000];
    //不断接收数据
    while(1)
    {
        memset(buffer,0,sizeof(buffer));
        int len = recv(conn, buffer, sizeof(buffer),0);
        //recv返回值小于等于0，退出
        if(len<=0)
            break;
        cout<<"收到服务器发来的信息："<<buffer<<endl;
    }
}

int main()
{
    client clnt(8023,"127.0.0.1");
    clnt.run();
}